package com.chen.common.security.config;

import com.chen.common.security.component.AuthAccessDeniedHandler;
import com.chen.common.security.component.AuthExceptionEntryPoint;
import com.chen.common.security.component.PermitAllUrlResolver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;

import javax.annotation.Resource;

@Slf4j
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Resource
    private TokenStore tokenStore;
    @Resource
    private PermitAllUrlResolver permitAllUrlResolver;
    @Value("${spring.application.name}")
    private String applicationName;

    @Resource
    AuthExceptionEntryPoint authExceptionEntryPoint;
    @Resource
    AuthAccessDeniedHandler authAccessDeniedHandler;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        // 允许使用iframe 嵌套，避免swagger-ui 不被加载的问题
        http.headers().frameOptions().disable();
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http.authorizeRequests();
        // 配置对外暴露接口
        permitAllUrlResolver.registry(registry);
        registry.anyRequest().authenticated().and().csrf().disable();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.tokenStore(tokenStore);
        resources.resourceId(applicationName);

        resources.authenticationEntryPoint(authExceptionEntryPoint)
                .accessDeniedHandler(authAccessDeniedHandler);
    }

}